package com.cunjiankang.ui;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import com.cunjiankang.App;
import com.cunjiankang.R;
import com.cunjiankang.bean.request.BaseRequest;
import com.cunjiankang.bean.response.BaseResponse;
import com.cunjiankang.bean.response.VersionResponse;
import com.cunjiankang.util.*;
import com.cunjiankang.view.CustomProgressDialog;
import com.cunjiankang.view.RequestDialog;
import com.google.gson.Gson;
import org.kymjs.kjframe.http.HttpCallBack;
import org.kymjs.kjframe.ui.BindView;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.KJLoger;
import org.kymjs.kjframe.utils.SystemTool;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liyongqiang
 * @ClassName: CardLoginActivity
 * @Description:
 * @date 2015-3-5 下午11:39:15
 */
@SuppressLint("HandlerLeak")
public class CardLoginActivity extends BaseActivity implements OnClickListener {

    @BindView(id = R.id.edit_card)
    private EditText editCard;
    @BindView(id = R.id.btn_account_login, click = true)
    private Button accountLogin;
    private boolean isBoot;
    private String groupId;

    @Override
    protected void onStart() {
        super.onStart();
        Contants.starTime = System.currentTimeMillis();
        Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == Timer.MSG_CLOSE) {
                    PreferenceUtil.remove(App.i(), Contants.SP.login_id);
                    PreferenceUtil.remove(App.i(), Contants.SP.username);
                    PreferenceUtil.remove(App.i(), Contants.SP.integral);
                    PreferenceUtil.remove(App.i(), Contants.SP.cardnum);
                    skipActivity(CardLoginActivity.this, ADActivity.class);
                    Contants.isADStart = true;
                }
            }
        };
        Timer timer = new Timer(handler);
        handler.postDelayed(timer, Timer.TIME);
    }

    @Override
    public void setRootView() {
        setContentView(R.layout.activity_card_login);
        super.setRootView();
        PreferenceUtil.write(this, Contants.SP.notFirst, true);
        isBoot = getIntent().getBooleanExtra("isBoot", false);
        groupId = PreferenceUtil.readString(this, Contants.SP.local_grubid, "");
        if (TextUtils.isEmpty(groupId)) {
            skipActivity(this, WelcomeActivity.class);
        }
        queryIP(groupId);
    }

    @Override
    public void initWidget() {
        super.initWidget();
        editCard.setInputType(InputType.TYPE_NULL);
        editCard.addTextChangedListener(textWatcher);
    }

    TextWatcher textWatcher = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence str, int arg1, int arg2, int arg3) {
            if (!"".equals(str.toString())) {
                editCard.removeTextChangedListener(this);
                handler.sendEmptyMessageDelayed(2, 2000);
            }
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                      int arg3) {

        }

        @Override
        public void afterTextChanged(Editable arg0) {

        }
    };

    private void queryVersion() {
        BaseRequest baseRequest = new BaseRequest();
        baseRequest.type = Contants.ApiKey.getCXJVersion;
        HttpUtil.post(baseRequest, new HttpCallBack() {
            @Override
            public void onSuccess(String t) {
                super.onSuccess(t);
                KJLoger.debug("*****************************************:" + t);
                BaseResponse response = new Gson().fromJson(t,
                        BaseResponse.class);
                if (response.flag.equals(VersionResponse.flag_success)) {
                    System.out.println("版本请求恢复："+response.version);
                    System.out.println("请求版本号是否相同："+SystemTool.getAppVersion(CardLoginActivity.this).equals(
                            response.version));
                    if (!SystemTool.getAppVersion(CardLoginActivity.this).equals(
                            response.version)) {
                        showUpdate(response.url);
                    }
                }
            }
        }, CardLoginActivity.this);
    }

    private void showUpdate(final String url) {
        RequestDialog.show(CardLoginActivity.this, getString(R.string.update_msg),
                getString(R.string.update), getString(R.string.cancel),
                new RequestDialog.RequestDialogListener() {
                    @Override
                    public void accept(boolean accept) {
                        if (accept) {
                            Intent intent = new Intent(CardLoginActivity.this,
                                    UpdateService.class);
                            intent.putExtra("Key_App_Name",
                                    getString(R.string.app_name));
                            intent.putExtra("Key_Down_Url", url);
                            startService(intent);
                        }
                    }
                });
    }

    private void queryIP(final String groupId) {
        final BaseRequest baseRequest = new BaseRequest();
        final Dialog dialog = CustomProgressDialog.createDialog(this)
                .setMessage(R.string.loading_ip);
//        dialog.show();
        baseRequest.type = Contants.ApiKey.getDrugip;
        baseRequest.group_id = groupId;
        HttpUtil.post(baseRequest, new HttpCallBack() {
            @Override
            public void onSuccess(String t) {
                super.onSuccess(t);
                KJLoger.debug(baseRequest.type + ":" + t);
                try {
                    BaseResponse baseResponse = new Gson().fromJson(t, BaseResponse.class);
                    if (baseResponse.flag.equals(BaseResponse.flag_success)) {
                        String url = baseResponse.url;
                        String[] urls = url.split(":");
                        String ip = "";
                        String port = "";
                        if (urls.length == 2) {// 不包含http 如10.340.450.23:8080
                            ip = url.split(":")[0];
                            port = url.split(":")[1];
                        } else {// 包含http 如http://10.340.450.23:8080
                            ip = url.split(":")[1].substring(2);
                            port = url.split(":")[2];
                        }
                        PreferenceUtil.write(CardLoginActivity.this, Contants.SP.local_ip, ip);
                        PreferenceUtil.write(CardLoginActivity.this, Contants.SP.local_port, port);
                    } else {
                        String tip = getString(R.string.get_ip_error);
//                        ViewInject.toast(tip);
                        handler.sendEmptyMessageDelayed(3, 5000);
                    }
                } catch (Exception e) {
                    dialog.dismiss();
                    String tip = getString(R.string.get_ip_error);
//                    ViewInject.toast(tip);
                    handler.sendEmptyMessageDelayed(3, 5000);
                }
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                String tip = getString(R.string.get_ip_error);
//                ViewInject.toast(tip);
                handler.sendEmptyMessageDelayed(3, 5000);
            }

            @Override
            public void onFinish() {
                super.onFinish();
                dialog.dismiss();
            }
        }, CardLoginActivity.this);
    }

    private void cardLogin(final String card) {
        BaseRequest baseRequest = new BaseRequest();
        baseRequest.type = Contants.ApiKey.unpwdlogin;
        baseRequest.card = card;
        final Dialog dialog = CustomProgressDialog.createDialog(this)
                .setMessage(R.string.loading_login);
        dialog.show();
        HttpUtil.post(baseRequest, new HttpCallBack() {
            @Override
            public void onSuccess(String t) {
                super.onSuccess(t);
                BaseResponse response = new Gson().fromJson(t,
                        BaseResponse.class);
                if (response.flag.equals(BaseResponse.flag_success)) {
                    PreferenceUtil.write(CardLoginActivity.this,
                            Contants.SP.cardnum, card);
                    PreferenceUtil.write(CardLoginActivity.this,
                            Contants.SP.login_id, card);
                    if (null != response.name && !"".equals(response.name)) {
                        PreferenceUtil.write(CardLoginActivity.this,
                                Contants.SP.username, response.name);
                    } else {
                        PreferenceUtil.write(CardLoginActivity.this,
                                Contants.SP.username, card);
                    }

                    skipActivity(CardLoginActivity.this, MainActivity.class);

                } else {
                    ViewInject.toast(getString(R.string.card_login_error));
                }
                editCard.setText("");
                editCard.addTextChangedListener(textWatcher);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                KJLoger.debug(t.toString());
                if (SystemTool.checkNet(CardLoginActivity.this)) {
                    ViewInject.toast(getString(R.string.login_error));
                } else {
                    ViewInject.toast(getString(R.string.net_error));
                }
                editCard.setText("");
                editCard.addTextChangedListener(textWatcher);
            }

            @Override
            public void onFinish() {
                super.onFinish();
                dialog.dismiss();
            }
        }, CardLoginActivity.this);
    }

    @Override
    public void widgetClick(View v) {
        super.widgetClick(v);
        switch (v.getId()) {
            case R.id.btn_account_login:
                skipActivity(this, LoginActivity.class);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        editCard.setText("");
        queryVersion();
    }

    ;

    Handler handler = new Handler() {

        public void handleMessage(Message msg) {
            if (msg.what == 2) {
                String card = editCard.getText().toString()
                        .replaceAll("[a-zA-Z]", "");
//				int index = getSpaceIndex(card);
//				if (index != -1) {
//					card = card.substring(0, index);
//				}
//
                List<Character> characters = new ArrayList<Character>();
                char[] chrs = card.toCharArray();

                for (char a : chrs) {
                    try {
                        Integer.parseInt(String.valueOf(a));
                        characters.add(a);
                    } catch (Exception e) {
                        System.out.println(e);
                    }
                }

                char[] chars = new char[characters.size()];
                for (int i = 0; i < characters.size(); i++) {
                    chars[i] = characters.get(i);
                }
                String tempString = String.valueOf(chars);


                if (null != groupId && groupId.startsWith("184")) {
                    tempString = "G" + tempString;
                }
                cardLogin(tempString);
            } else if (msg.what == 3) {
                if (CardLoginActivity.this != null) {
                    queryIP(groupId);
                }
            }
        }

        ;
    };

    public int getSpaceIndex(String str) {
        char[] chrs = str.toCharArray();
        for (int i = 0; i < chrs.length; i++) {
            if (String.valueOf(chrs[i]).equals(" ")) {
                return i;
            }
        }
        return -1;
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        handler.removeMessages(1);
    }

}
